#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.${parentArtifactId}.modules.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import ${package}.${parentArtifactId}.common.base.SuperController;
import ${package}.${parentArtifactId}.common.bean.PageData;
import ${package}.${parentArtifactId}.common.bean.PageParam;
import ${package}.${parentArtifactId}.libcommon.annotation.Auth;
import ${package}.${parentArtifactId}.libcommon.annotation.Log;
import ${package}.${parentArtifactId}.libcommon.bean.R;
import ${package}.${parentArtifactId}.libcommon.constant.Constants;
import ${package}.${parentArtifactId}.libcommon.util.DateUtils;
import ${package}.${parentArtifactId}.libcommon.util.TreeUtil;
import ${package}.${parentArtifactId}.modules.sys.service.SysOrgService;
import ${package}.${parentArtifactId}.modules.sys.entity.SysOrg;
import ${package}.${parentArtifactId}.modules.sys.vo.SysOrgVo;
import ${package}.${parentArtifactId}.modules.sys.dto.SysOrgDTO;
import ${package}.${parentArtifactId}.modules.sys.query.SysOrgQuery;
import ${package}.${parentArtifactId}.modules.sys.vo.SysOrgTreeVo;
import ${package}.${parentArtifactId}.modules.sys.vo.TreeSelectVo;
import ${package}.${parentArtifactId}.modules.sys.converter.SysOrgConverter;
import ${package}.${parentArtifactId}.modules.sys.excel.SysOrgImporter;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import io.swagger.annotations.*;
import ${package}.${parentArtifactId}.libcommon.excel.ExcelUtil;
import ${package}.${parentArtifactId}.libcommon.component.storage.bean.UploadResult;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

/**
 * @Classname SysOrgController
 * @Description 组织机构表 Controller
 * @Author Created by xudp (alias:孤傲苍狼) 290603672@qq.com
 * @Date 2020-10-15
 * @Version 1.0
 */
@Api(tags = "SysOrg管理")
//@Auth(name = "SysOrg管理")//在类上标注了@Auth注解后这个类下的所有接口将被AuthInterceptor拦截进行访问权限控制
@RestController
@RequestMapping("/api/sys/org")
public class SysOrgController extends SuperController{

    @Autowired
    private SysOrgService sysOrgService;

    /**
     * 创建
     * @param sysOrg
     * @return
     */
    @ApiOperation("新增")
    @Log(operation="创建",remark = "创建SysOrg",moduleName = "SysOrg管理") //在方法上标注@Log注解用于记录操作日志
    @PostMapping
    public R<Void> create(@RequestBody @Validated(Constants.Create.class) SysOrgDTO sysOrg){
        sysOrgService.create(sysOrg);
        return R.ok();
    }

    /**
     * 更新
     * @param sysOrg
     * @return
     */
    @ApiOperation("修改")
    @Log(operation="修改",remark = "修改SysOrg",moduleName = "SysOrg管理")
    @PutMapping
    public R<Void> update(@RequestBody @Validated(Constants.Update.class) SysOrgDTO sysOrg){
        sysOrgService.update(sysOrg);
        return R.ok();
    }

    /**
     * 根据ID查找
     * @param id
     * @return
     */
    @ApiOperation("根据ID查找")
    @Auth(isAuth = false)//不进行权限控制
    @GetMapping("/{id}")
    public R<SysOrgVo> get(@PathVariable("id") Long id){
        SysOrgVo sysOrgVo = sysOrgService.getSysOrgById(id);
        return R.ok(sysOrgVo);
    }

    /**
     * 根据条件查询
     * @return
     */
    @ApiOperation("根据条件查询")
    @Auth(isAuth = false)//不进行权限控制
    @GetMapping
    public R<List<SysOrgVo>> get(SysOrgQuery query) {
        //构建查询条件
        QueryWrapper<SysOrg> queryWrapper = buildQueryWrapper(query);
        List<SysOrgVo> sysOrgListVo = sysOrgService.getList(queryWrapper);
        return R.ok(sysOrgListVo);
    }

    /**
    * 根据ID批量删除
    * @param ids
    * @return
    */
    @ApiOperation("根据ID批量删除")
    @Log(operation="删除",remark = "根据ID删除SysOrg",moduleName = "SysOrg管理")
    @DeleteMapping("/{ids}")
    public R<Void> delete(@PathVariable("ids") Long[] ids){
        if(ids.length==1){
            sysOrgService.deleteById(ids[0]);
        }else {
            List<Long> idList = Arrays.asList(ids);
            sysOrgService.deleteByIds(idList);
        }
        return R.ok();
    }


    @ApiOperation("导入数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "isCovered",value = "是否覆盖，true:覆盖,false:不覆盖",required = true),
            @ApiImplicitParam(name = "parentId",value = "父级ID")
    })
    @PostMapping("/importData")
    public R<Void> importData(@ApiParam(value = "Excel文件", required = true) @RequestParam(value = "file") MultipartFile file, Boolean isCovered,String parentId) {
        Long pId = 0L;
        if(StrUtil.isNotBlank(parentId) && !parentId.equals("undefined")){
            pId = Long.parseLong(parentId);
        }
        SysOrgImporter sysOrgImporter = new SysOrgImporter(sysOrgService, isCovered,pId);
        ExcelUtil.save(file, sysOrgImporter, SysOrgDTO.class);
        return R.success("导入成功");
    }

    @ApiOperation("获取数据导入模板")
    @GetMapping("/import/template")
    public void getImportTemplate(HttpServletResponse response) {
        List<SysOrgDTO> list = new ArrayList<>();
        ExcelUtil.export(response, "SysOrg数据导入模板", "SysOrg数据表", list, SysOrgDTO.class);
    }
    /**
      * 分页查询
      * @return
      */
    @ApiOperation("分页查询")
    @Auth(isAuth = false)//不进行权限控制
    @GetMapping(value = "/list")
    public R<PageData<SysOrgVo>> pageList(SysOrgQuery query, PageParam pageParam){
        //构建查询条件
        QueryWrapper<SysOrg> queryWrapper = buildQueryWrapper(query);
        PageData<SysOrgVo> pageData = sysOrgService.pageList(pageParam,queryWrapper);//mybatisPlus分页查询
        return R.ok(pageData);
    }


    @ApiOperation("获取树列表")
    @Auth(isAuth = false)//不进行权限控制
    @GetMapping("/treeList")
    public R<List<SysOrgTreeVo>> treeList(SysOrgQuery query){
        //构建查询条件
        QueryWrapper<SysOrg> queryWrapper = buildTreeQueryWrapper(query);
        return R.ok(TreeUtil.buildTree(sysOrgService.getTreeVoList(queryWrapper)));
    }

    @ApiOperation("获取下拉树列表")
    @Auth(isAuth = false)//不进行权限控制
    @GetMapping("/treeSelect")
    public R<List<TreeSelectVo>> treeSelect(SysOrgQuery query) {
        QueryWrapper<SysOrg> queryWrapper = buildTreeQueryWrapper(query);
        return R.ok(SysOrgConverter.build().treeSelectListVo(sysOrgService.getTreeVoList(queryWrapper)));
    }

    @ApiOperation("根据ID获取节点信息以及子节点信息")
    @ApiImplicitParam(name = "id",value = "区域ID",required = true)
    @Auth(isAuth = false)//不进行权限控制
    @GetMapping("/tree/{id}")
    public R<List<SysOrgTreeVo>> getSubNodeListById(@PathVariable("id") Long id) {
        List<SysOrgTreeVo> treeVoList = sysOrgService.getSubNodeListById(id);
        return R.ok(TreeUtil.buildTree(treeVoList));
    }

    @ApiOperation("根据ID获取树")
    @ApiImplicitParam(name = "id",value = "ID",required = true)
    @Auth(isAuth = false)//不进行权限控制
    @GetMapping("/tree/org/{id}")
    public R<SysOrgTreeVo> getTreeById(@PathVariable("id") Long id) {
        SysOrgTreeVo treeVo = sysOrgService.getTreeById(id);
        return R.ok(treeVo);
    }

    /**
    * 构建查询条件QueryWrapper
    * @param query
    * @return
    */
    private QueryWrapper<SysOrg> buildTreeQueryWrapper(SysOrgQuery query) {
        QueryWrapper<SysOrg> queryWrapper = new QueryWrapper<>();
        //构建查询条件
        if(query != null){
            //构建查询条件
            if(query.getId() != null){
                //查询出所有的父节点
                List<SysOrgTreeVo> treeVos = sysOrgService.getParentNodeTreeListById(query.getId());
                if(CollectionUtil.isNotEmpty(treeVos)){
                    List<Long> parentIds = new ArrayList<>();
                    treeVos.forEach(treeVo -> {
                        parentIds.add(treeVo.getId());
                    });
                    queryWrapper.eq(SysOrg.PARENT_ID,0).or().isNull(SysOrg.PARENT_ID).or().in(SysOrg.ID,parentIds);
                }else {
                    queryWrapper.eq(SysOrg.PARENT_ID,0).or().isNull(SysOrg.PARENT_ID);
                }
            }
            if(query.getParentId() != null){
                queryWrapper.eq(SysOrg.PARENT_ID,query.getParentId());
            }
        }
        return queryWrapper;
    }
    /**
     * 构建查询条件QueryWrapper
     * @param query
     * @return
     */
    private QueryWrapper<SysOrg> buildQueryWrapper(SysOrgQuery query) {
        QueryWrapper<SysOrg> queryWrapper = new QueryWrapper<>();
        //构建查询条件
        if(query.getId() != null){
            queryWrapper.eq(SysOrg.ID,query.getId());
        }
        if(query.getParentId() != null){
            queryWrapper.eq(SysOrg.PARENT_ID,query.getParentId());
        }
        if(StrUtil.isNotBlank(query.getParentName())){
            queryWrapper.like(SysOrg.PARENT_NAME,query.getParentName());
        }
        if(StrUtil.isNotBlank(query.getName())){
            queryWrapper.like(SysOrg.NAME,query.getName());
        }
        if(query.getOrderNum() != null){
            queryWrapper.eq(SysOrg.ORDER_NUM,query.getOrderNum());
        }
        if(StrUtil.isNotBlank(query.getLeader())){
            queryWrapper.like(SysOrg.LEADER,query.getLeader());
        }
        if(StrUtil.isNotBlank(query.getPhone())){
            queryWrapper.like(SysOrg.PHONE,query.getPhone());
        }
        if(StrUtil.isNotBlank(query.getEmail())){
            queryWrapper.like(SysOrg.EMAIL,query.getEmail());
        }
        if(query.getStatus() != null){
            queryWrapper.eq(SysOrg.STATUS,query.getStatus());
        }
        if(query.getType() != null){
            queryWrapper.eq(SysOrg.TYPE,query.getType());
        }
        if(query.getRegionId() != null){
            queryWrapper.eq(SysOrg.REGION_ID,query.getRegionId());
        }
        if(query.getTenantId() != null){
            queryWrapper.eq(SysOrg.TENANT_ID,query.getTenantId());
        }
        if(ArrayUtil.isNotEmpty(query.getIds())){
            queryWrapper.in(SysOrg.ID,Arrays.asList(query.getIds()));
        }
        return queryWrapper;
    }
}